package com.forum.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;



public class RedisClient {

	private Jedis jedis;//???????????????
    private JedisPool jedisPool;//??????????
    private ShardedJedis shardedJedis;//?????????????
    private ShardedJedisPool shardedJedisPool;//????????
    
    public RedisClient() 
    { 
        initialPool(); 
        initialShardedPool(); 
        shardedJedis = shardedJedisPool.getResource(); 
        jedis = jedisPool.getResource(); 
        jedis.auth("vincent");
        
        
    } 
 
    /**
     * ????????????
     */
    private void initialPool() 
    { 
        // ??????? 
        JedisPoolConfig config = new JedisPoolConfig(); 
        config.setMaxActive(20); 
        config.setMaxIdle(5); 
        config.setMaxWait(1000l); 
        config.setTestOnBorrow(false); 
        jedisPool = new JedisPool(config,"115.159.158.26",9736);
        
    }
    
    /** 
     * ?????????? 
     */ 
    private void initialShardedPool() 
    { 
        // ??????? 
        JedisPoolConfig config = new JedisPoolConfig(); 
        config.setMaxActive(20); 
        config.setMaxIdle(5); 
        config.setMaxWait(1000l); 
        config.setTestOnBorrow(false); 
        
        // slave???? 
        List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); 
        shards.add(new JedisShardInfo("115.159.158.26", 9736,"master")); 
        // ????? 
        shardedJedisPool = new ShardedJedisPool(config, shards); 
        
    } 

    public void show(String name,String email,String passwd,String url) {     

    	if(Validate(email, passwd))
    	{
    		//renameUsername(name);
    		Regist( renameUsername(name), email, passwd,url);
    	}
    	jedisPool.returnResource(jedis);
        shardedJedisPool.returnResource(shardedJedis);

    } 

    private void Regist(String name,String email,String passwd,String url) {
      String hashpasswd = BCrypt.hashpw(passwd, BCrypt.gensalt());
      jedis.hincrBy("global", "nextUid", 1);//????global??nextUid
      String uid=jedis.hget("global", "nextUid");
      jedis.hincrBy("global", "userCount", 1);//????global??userCount
      String membercount=jedis.hget("global", "userCount");
      Double score=Double.parseDouble(uid);
  	  jedis.zadd("username:uid",score , name);//????username??uid
   	  jedis.zadd("username:sorted",0 , name+":"+uid);//????username??sorted
  	  jedis.zadd("userslug:uid", score, name.toLowerCase());//????userslug??uid
  	  Date str=new Date();
  	  jedis.zadd("users:joindate", (double)str.getTime(),uid);
  	  jedis.zadd("users:reputation", 0,uid);
  	  jedis.zadd("users:postcount", 0, uid);
  	  jedis.zadd("users:online", (double)str.getTime(),uid);
  	  
  	  jedis.hset("group:registered-users", "memberCount", membercount);
  	  jedis.hset("group:registered-users", "memberCount", membercount);
  	  jedis.zadd("group:registered-users:members", (double)str.getTime(), uid);
  	  jedis.zadd("email:uid", score, email);
  	  jedis.zadd("email:sorted", 0,email+":"+uid);
  	  HashMap<String, String> map=new HashMap<String, String>();
  	  map.put("uid", uid);
  	  map.put("userslug",name.toLowerCase());
  	  map.put("postcount","0");
  	  map.put("uploadedpicture",url);
  	  map.put("password", hashpasswd);
  	  map.put("passwordExpiry","0");
  	  map.put("fullname", "");
  	  map.put("reputation", "0");
  	  map.put("picture", url);
  	  map.put("profileviews", "0");
  	  map.put("lastposttime", "0");
  	  map.put("banned", "0");
  	  map.put("joindate",Long.toString(str.getTime()));
  	  map.put("gravatarpicture","");
  	  map.put("website", "");
  	  map.put("email", email);
  	  map.put("status", "online");
  	  map.put("birthday", "");
  	  map.put("lastonline",Long.toString(str.getTime()));
  	  map.put("signature", "");
  	  map.put("location","");
  	  map.put("username", name);
  	  map.put("topiccount", "0");
  	  jedis.hmset("user:"+uid, map);
//  	  System.out.println("???????");
    }
    
    private boolean Validate(String email,String passwd)
    { 
    	
    	try { // try???????  
            
    		if(jedis.zrank("email:uid", email)!=null) throw new Exception(); // ???throw????????   
        }  
        catch (Exception e) { // catch?????  
            System.out.println("?ú?????????");  
            return false;
        }  
    	
    	try { // try???????  
            
    		if(passwd.length()<6) throw new Exception(); // ???throw????????   
        }  
        catch (Exception e) { // catch?????  
            System.out.println("????????");  
            return false;
        } 
    	
    	return true;
    		
    	
    }
    
    private String renameUsername(String username){
    	String newusername=username;
    	int num;
    	while(jedis.zrank("username:uid", newusername)!=null||jedis.zrank("userslug:uid", newusername.toLowerCase())!=null){
    		num=(int) (Math.random() * 255+ 1);
    		newusername=username+ num;
    	}	
    	return newusername;
    }
 
}


